package com.squareshoot.picCheckin;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;

public class Home extends Activity {
	private static final int GROUP1 = 111;
	private static final int ID_PARAMS = 1110;
	private static final int ID_LOGOUT = 1111;
	private static final int PREFERENCES = 0;
	private static final int CHOOSEVENUE = 10;
	private static final int ID_QUIT = 1112;
	private final int DIALOG_QUIT = 11;
	private final int DIALOG_LOGOUT = 12;
	GridView grid_main;
	Bundle monBundle;

	String username;
	String password;
	String nomPrenom = null;
	String picuserid,fsid;

	Bitmap bm;


	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		
		monBundle=this.getIntent().getExtras();
		username = monBundle.getString("username");
		password = monBundle.getString("password");
		
		findViewById(R.id.home_venues_image).setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				startChooseVenue();
			}
		});
		
		findViewById(R.id.home_friends_image).setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				startFriendsAndPhotos();
			}
		});

		findViewById(R.id.home_public_tl_image).setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				startPublicTimeline();
			}
		});

		findViewById(R.id.home_friends_tl_image).setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				startFriendsTimeline();
			}
		});

		String userProfile = monBundle.getString("user");


		String photoURL = null;
		try {
			JSONObject jUser=new JSONObject(userProfile);
			nomPrenom=jUser.getString("firstname");
			picuserid = jUser.getString("picuserid");
			fsid = jUser.getString("id");
			if(jUser.has("lastname")){
				nomPrenom += " "+jUser.getString("lastname");
			}
			photoURL = jUser.getString("photo");
			
			if(jUser.getJSONObject("settings").getString("sendtotwitter").compareTo("true")==0)
				monBundle.putBoolean("sendtotwitter",true);
			else
				monBundle.putBoolean("sendtotwitter",false);
			if(jUser.getJSONObject("settings").getString("sendtofacebook").compareTo("true")==0)
				monBundle.putBoolean("sendtofacebook",true);
			else
				monBundle.putBoolean("sendtofacebook",false);
		} catch (JSONException e) {
			if(Common.HIGHDEBUG)
				Log.e(Common.TAG,"Home : "+e.getMessage());
		}

		//telecharge la photo et la stocke sur la SD, ou la prend direct sur la sd si elle existe
		bm = Common.getCachedPicture(photoURL);
	}

	//Lance l'Activity ChooseVenue
	private void startChooseVenue(){

		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"Login OK, starting Intent ChooseVenue");
		Intent i = new Intent(Home.this,ChooseVenue.class);		
		i.putExtras(monBundle);
		startActivityForResult(i,CHOOSEVENUE);
	}

	private void startFriendsAndPhotos(){
		if(Common.HIGHDEBUG)
			Log.w(Common.TAG,"On startFriendsAndPhotos");
		Intent i=new Intent(Home.this,FriendsAndPhotos.class);
		Bundle bundle = new Bundle();
		bundle.putParcelable("photo", bm);
		bundle.putString("nomPrenom",nomPrenom);
		bundle.putString("username",username);
		bundle.putString("password",password);
		bundle.putString("picuserid",picuserid);
		bundle.putString("fsid",fsid);
		bundle.putBoolean("me",true);
		i.putExtras(bundle);
		startActivity(i);
	}

	private void startPublicTimeline(){
		Intent i=new Intent(Home.this,PublicTimeline.class);
		Bundle bundle = new Bundle();
		bundle.putString("username",username);
		bundle.putString("password",password);
		i.putExtras(bundle);
		startActivity(i);
	}
	
	private void startFriendsTimeline(){
		Intent i=new Intent(Home.this,FriendsTimeline.class);
		Bundle bundle = new Bundle();
		bundle.putString("username",username);
		bundle.putString("password",password);
		i.putExtras(bundle);
		startActivity(i);
	}
	
//	@Override
//	public boolean onKeyDown(int code,KeyEvent event){
//		if(event.getKeyCode()==4){
//			//touche BACK, on quitte
//			showDialog(DIALOG_QUIT);
//			return true;
//		}
//		return false;
//	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_QUIT:
			//Confirmation pour quitter l'appli (quand on appuie sur le bouton BACK)
			AlertDialog.Builder builderQuit = new AlertDialog.Builder(this);
			builderQuit.setTitle(getString(R.string.quit))
			.setCancelable(false)
			.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					finish();
				}
			})
			.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alertQuit = builderQuit.create();
			return alertQuit;
		case DIALOG_LOGOUT:
			AlertDialog.Builder builderLogout = new AlertDialog.Builder(this);
			builderLogout.setTitle(getString(R.string.logout)+"?")
			.setCancelable(false)
			.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					ProfileDb mDbHelper = new ProfileDb(Home.this);
					mDbHelper.open();
					mDbHelper.dropProfileTable();
					mDbHelper.close();

					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Home.this);
					Editor editor = prefs.edit();
					editor.remove("emailPref");
					editor.remove("passwordPref");
					editor.putBoolean("isAuthent", false);
					editor.commit();	
					finish();    	   
				}
			})
			.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alertLogout = builderLogout.create();
			return alertLogout;
		}
		return null;
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(GROUP1,ID_PARAMS,3, getString(R.string.options)).setIcon(R.drawable.ic_menu_preferences);
		menu.add(GROUP1,ID_LOGOUT,2, getString(R.string.logout)).setIcon(R.drawable.ic_menu_logout);
		menu.add(GROUP1,ID_QUIT,1, getString(R.string.exitButton)).setIcon(R.drawable.ic_menu_logout);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ID_PARAMS:
			Intent params = new Intent(Home.this,PrefsActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("username",username);
			bundle.putString("password",password);
			params.putExtras(bundle);
			startActivityForResult(params,PREFERENCES);
			return true;
		case ID_LOGOUT:
			showDialog(DIALOG_LOGOUT);
			return true;
		case ID_QUIT:
			showDialog(DIALOG_QUIT);
			return true;
		}
		return false;
	}
	
	//Retour des activity
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		Bundle extras = null;
		if(intent!=null){
			extras = intent.getExtras();
		}

		Log.d(Common.TAG,"ChooseVenue : onActivityResult");
		switch(requestCode) {
		case PREFERENCES:
			if(extras!=null){
				if(extras.get("from").equals("Prefs")){
					Log.i(Common.TAG,"on vient de supprimer les Prefs = on quitte");
					finish();  
				}
			}
			break;
		}
	}
}
